import { Toast } from "antd-mobile";
import Locale from "../locales";
import { REFRESH_TOKEN_INTERVAL } from "@/constant/config";
import packageJson from "../../package.json";
import { useAuthStore } from "@/store";

export function getProperty<T, K extends keyof T>(
  obj: T,
  key: K,
): T[K] | undefined {
  return typeof obj === "object" && obj !== null ? obj[key] : undefined;
}

export function getVersion(): number {
  return Number(packageJson.version);
}

export function isMobile(): boolean {
  const userAgent: string = globalThis.navigator?.userAgent?.toLowerCase();
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    userAgent,
  );
  return false;
}
export function isWebView(): boolean {
  const authStore = useAuthStore.getState();
  const username: string = authStore.user?.username;
  return username === "engineer_admin";
}
export function getTokenExpiration(): number {
  return Date.now() + REFRESH_TOKEN_INTERVAL;
}

export function vConsole(): void {
  if (process.env.NODE_ENV === "development") {
    if (typeof window !== "undefined")
      window.console.log = function (log) {
        window?.parent.postMessage({ message: log }, "*"); // 将子窗口的信息发送到父窗口
      };
  }
}

export function trimTopic(topic: string) {
  const s = topic.split("");
  let lastChar = s.at(-1); // 获取 s 的最后一个字符
  let pattern = /[，。！？、]/; // 定义匹配中文标点符号的正则表达式
  while (lastChar && pattern.test(lastChar!)) {
    s.pop();
    lastChar = s.at(-1);
  }

  return s.join("");
}

export function inNestedIframe(): boolean {
  try {
    return window.self !== window.top;
  } catch (e) {
    // 发生异常时，说明当前页面被嵌套在一个不同域名的 iframe 中，直接返回 true
    return true;
  }
}

export async function copyToClipboard(text: string) {
  let textArea = document.createElement("textarea");
  textArea.value = text;
  // 使text area不在viewport，同时设置不可见
  textArea.style.position = "absolute";
  textArea.style.opacity = "0";
  textArea.style.left = "-999999px";
  textArea.style.top = "-999999px";
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  try {
    await new Promise((res, rej) => {
      // 执行复制命令并移除文本框
      document.execCommand("copy") ? res(null) : rej();
      textArea.remove();
    });
    Toast.show({
      icon: "success",
      content: Locale.Copy.Success,
    });
  } catch (err) {
    Toast.show({
      icon: "success",
      content: Locale.Copy.Failed,
    });
  }
}

export function downloadAs(text: string, filename: string) {
  var blob = new Blob([text], { type: "text/plain;charset=utf-8" });
  var downloadLink = document.createElement("a");
  downloadLink.href = window.URL.createObjectURL(blob);
  console.log(`downloadLink:${downloadLink.href}`);
  downloadLink.download = filename;
  downloadLink.target = "_top";
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
}
export function isIos(): boolean {
  const userAgent = navigator.userAgent.toLowerCase();
  return /iphone|ipad|ipod/.test(userAgent);
}
export function isAndroid(): boolean {
  const userAgent = navigator.userAgent.toLowerCase();
  console.log("🚀 ~ isAndroid ~ userAgent:", userAgent);
  return /android/.test(userAgent);
}
export function isIosApp(): boolean {
  return isWebView() && isIos();
}
export function isAndroidApp(): boolean {
  return isWebView() && isAndroid();
}
export function selectOrCopy(el: HTMLElement, content: string) {
  const currentSelection = window.getSelection();

  if (currentSelection?.type === "Range") {
    return false;
  }

  copyToClipboard(content);

  return true;
}

export function queryMeta(key: string, defaultValue?: string): string {
  let ret: string;
  if (document) {
    const meta = document.head.querySelector(
      `meta[name='${key}']`,
    ) as HTMLMetaElement;
    ret = meta?.content ?? "";
  } else {
    ret = defaultValue ?? "";
  }

  return ret;
}

let currentId: string;
export function getCurrentCommitId() {
  if (currentId) {
    return currentId;
  }

  currentId = queryMeta("version");

  return currentId;
}

export function getBrowserUrlLengthLimit(): number {
  const userAgent = navigator.userAgent.toLowerCase();

  if (userAgent.indexOf("msie") !== -1 || userAgent.indexOf("trident") !== -1) {
    // Internet Explorer
    return 2083;
  } else if (userAgent.indexOf("chrome") !== -1) {
    // Chrome
    return 8192;
  } else if (userAgent.indexOf("firefox") !== -1) {
    // Firefox
    return 8192;
  } else if (userAgent.indexOf("safari") !== -1) {
    // Safari
    return 8192;
  } else {
    // 其他浏览器，返回一个较小的值作为保守估计
    return 2000;
  }
}
export function getByteLength(str: string): number {
  let byteLength: number = 0;
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i);
    if (charCode <= 0x7f) {
      byteLength += 1;
    } else if (charCode <= 0x7ff) {
      byteLength += 2;
    } else if (charCode <= 0xffff) {
      byteLength += 3;
    } else {
      byteLength += 4;
    }
  }
  return byteLength;
}

export const isUrlExceedLimit = (str: string): boolean => {
  const content: string = encodeURIComponent(str);
  if (getByteLength(content) >= getBrowserUrlLengthLimit()) {
    return true;
  }
  return false;
};

export const sleep = (ms: number): Promise<void> =>
  new Promise((resolve) => setTimeout(resolve, ms));
export function isTouchDevice(): boolean {
  return "ontouchstart" in window || navigator.maxTouchPoints > 0;
}
